const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

const accMul = (arg1, arg2) => {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try { m += s1.split(".")[1].length } catch (e) { };
  try { m += s2.split(".")[1].length } catch (e) { };
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

const accDiv = (arg1, arg2) => {
  var t1 = 0,
    t2 = 0,
    r1, r2;
  try { t1 = arg1.toString().split(".")[1].length; } catch (e) { }
  try { t2 = arg2.toString().split(".")[1].length; } catch (e) { }
  // with (Math) {
    r1 = Number(arg1.toString().replace(".", ""));
    r2 = Number(arg2.toString().replace(".", ""));
    return (r1 / r2) * Math.pow(10, t2 - t1);
  // }
}

const genSign = (params) => {
  var md5 = require('md5.min.js');

  var keys = new Array;
  for (var key in params) {
    keys.push(key);
  }
  keys.sort();
  
  var result = '';
  for (var i = 0; i < keys.length; i ++) {
    var key = keys[i];
    var value = params[key];
    if (key == 'sign' || key == 'token' || key == 'str' || key == 'version') {
      continue;
    }
    if (!value) {
      continue;
    }
    result += key + '=' + value + '&';
  }
  return md5(result);
}

module.exports = {
  formatTime: formatTime,
  accMul: accMul,
  accDiv: accDiv,
  genSign: genSign
}
